import DEFAULT_AVATAR from '@/assets/imgs/default-avatar.jpg';

import CommentCard from '@/components/CommentCard';
import PostCard from '@/components/PostCard';
import { listPostVoByPageUsingPost } from '@/services/backend/postController';
import { doPostFavourUsingPost } from '@/services/backend/postFavourController';
import { doThumbUsingPost1 } from '@/services/backend/postThumbController';
import { LikeOutlined, MessageOutlined, SearchOutlined, StarOutlined } from '@ant-design/icons';
import {
  Avatar,
  Card,
  Divider,
  Flex,
  Image,
  Input,
  List,
  message,
  Skeleton,
  Space,
  Typography,
} from 'antd';
import dayjs from 'dayjs';
import relativeTime from 'dayjs/plugin/relativeTime';
import React, { useEffect, useState } from 'react';
import InfiniteScroll from 'react-infinite-scroll-component';

dayjs.extend(relativeTime);

const EssayPostCard: React.FC = () => {
  //查询评论的排序规则
  const [postSortedField, setPostSortedField] = useState<string>('createTime');
  //评论数据
  const [postData, setPostData] = useState<API.PostVO[]>([]);
  //是否有更多评论
  const [hasMore, setHasMore] = useState<boolean>(true);
  //评论数量
  const [postCount, setPostCount] = useState<number>();
  //当前页
  const [current, setCurrent] = useState<number>(1);
  // 使用Map存储每个评论的回复状态，键为评论ID
  const [replyStates, setReplyStates] = useState<Map<number, boolean>>(new Map());
  // 输入框的宽度
  const [inputWidth, setInputWidth] = useState<number>(100);
  // 输入框的值
  const [inputValue, setInputValue] = useState<string>();

  /**
   * 加载评论数据
   * @param sortField 排序字段
   * @param pageNum 当前页面
   */
  const loadPostData = async (sortField: string, pageNum?: number, searchValue?: string) => {
    //默认分页大小
    const pageSize = 5;
    // 使用传入的页码或当前状态中的页码
    const currentPage = pageNum || current;

    try {
      const { code, data } = await listPostVoByPageUsingPost({
        sortField,
        sortOrder: 'descend',
        pageSize: pageSize,
        current: currentPage,
        content: searchValue || inputValue,
      });
      if (code === 0 && data) {
        // 如果是加载更多（页码大于1），则追加数据而不是替换
        if (currentPage > 1) {
          setPostData((prevData) => [...prevData, ...(data?.records ?? [])]);
        } else {
          setPostData(data?.records ?? []);
        }
        //还有更多post
        const hasMore = Number(data.current) < Number(data.pages);
        setHasMore(hasMore);
        //总数
        setPostCount(data.total);
      }
    } catch (e: any) {
      message.error(e.message);
    }
  };

  /**
   * 当Radio发生变化时,处理评论排序字段
   * @param value
   */
  const handlePostSortedFieldChange = (value: string) => {
    setPostSortedField(value);
    //获取评论数据
    loadPostData(value);
  };

  /**
   * 切换特定评论的回复状态
   * @param postId 评论ID
   */
  const toggleReplyState = (postId: number) => {
    setReplyStates((prevStates) => {
      const newStates = new Map(prevStates);
      newStates.set(postId, !prevStates.get(postId));
      return newStates;
    });
  };
  /**
   * 处理帖子点赞
   * @param postId
   */
  const handleThumb = async (postId: number) => {
    try {
      await doThumbUsingPost1({
        postId,
      });
      await loadPostData(postSortedField);
    } catch (e: any) {
      message.error(e.message);
    }
  };

  /**
   * 处理帖子收藏
   * @param postId
   */
  const handleFavour = async (postId: number) => {
    try {
      await doPostFavourUsingPost({
        postId,
      });
      await loadPostData(postSortedField);
    } catch (e: any) {
      message.error(e.message);
    }
  };

  /**
   * 初始化组件时加载的数据
   */
  useEffect(() => {
    // 初始化时重置页码为1
    setCurrent(1);
    loadPostData(postSortedField, 1);
  }, []);

  return (
    <Flex vertical={true} gap={16}>
      <div>
        <PostCard
          callback={async () => {
            await loadPostData(postSortedField);
          }}
        />
      </div>
      <div>
        <Card
          tabList={[
            {
              label: '最新',
              key: 'createTime',
            },
            {
              label: '最热',
              key: 'thumbNum',
            },
            {
              label: '精选',
              key: 'priority',
            },
          ]}
          onTabChange={handlePostSortedFieldChange}
          variant={'borderless'}
        >
          <Card
            id={'post-post-card'}
            title={<div>共{postCount}条帖子</div>}
            extra={
              <div className={' rounded-3xl pt-1 pb-1 pl-2 pr-2 bg-gray-100 flex items-center'}>
                <span className={'text-gray-500 ml-2'}>
                  <SearchOutlined />
                </span>
                <Input
                  value={inputValue}
                  style={{ width: `${inputWidth}px`, transition: 'width 0.3s' }}
                  onChange={(e) => {
                    // @ts-ignore
                    const value = e.target.value;
                    setInputValue(value);
                  }}
                  onPressEnter={() => {
                    // 重置页码
                    setCurrent(1);
                    //加载数据
                    loadPostData(postSortedField, 1, inputValue);
                  }}
                  onFocus={() => setInputWidth(180)} // 获得焦点时宽度变大
                  onBlur={() => setInputWidth(100)}
                  variant={'borderless'}
                />
              </div>
            }
            variant={'borderless'}
            style={{
              boxShadow: 'none',
            }}
            styles={{
              header: {
                borderBottom: 'none',
              },
            }}
          >
            {/*帖子*/}
            <InfiniteScroll
              dataLength={postData.length}
              next={async () => {
                // 计算下一页的页码
                const nextPage = current + 1;
                // 先更新状态
                setCurrent(nextPage);
                // 使用新的页码加载数据
                await loadPostData(postSortedField, nextPage);
              }}
              hasMore={hasMore}
              endMessage={
                <p style={{ textAlign: 'center' }}>
                  <Divider plain>已经到底了 🤐</Divider>
                </p>
              }
              loader={<Skeleton avatar paragraph={{ rows: 4 }} active />}
            >
              <List<API.PostVO>
                split={true}
                itemLayout={'vertical'}
                dataSource={postData}
                renderItem={(item, index) => {
                  const isReplying = replyStates.get(item?.id ?? -1) || false;
                  //获取评论的actions
                  const postActions: React.ReactNode[] = [];
                  //点赞展示
                  if (item.hasThumb) {
                    postActions.push(
                      <Typography.Link key={'thumb'} onClick={() => handleThumb(item?.id ?? -1)}>
                        <Space size={4}>
                          <LikeOutlined />
                          {item.thumbNum}
                        </Space>
                      </Typography.Link>,
                    );
                  } else {
                    postActions.push(
                      <a key={'thumb'} onClick={() => handleThumb(item?.id ?? -1)}>
                        <Space size={4}>
                          <LikeOutlined />
                          {item.thumbNum}
                        </Space>
                      </a>,
                    );
                  }
                  //收藏展示
                  if (item.hasFavour) {
                    postActions.push(
                      <Typography.Link key={'favour'} onClick={() => handleFavour(item?.id ?? -1)}>
                        <Space size={4}>
                          <StarOutlined />
                          {item.favourNum}
                        </Space>
                      </Typography.Link>,
                    );
                  } else {
                    postActions.push(
                      <a key={'favour'} onClick={() => handleFavour(item?.id ?? -1)}>
                        <Space size={4}>
                          <StarOutlined />
                          {item.favourNum}
                        </Space>
                      </a>,
                    );
                  }
                  //回复展示
                  if (isReplying) {
                    postActions.push(
                      <Typography.Link
                        key={'reply'}
                        onClick={() => toggleReplyState(item?.id ?? -1)}
                      >
                        <Space size={4}>
                          <MessageOutlined />
                          <span>收起评论</span>
                        </Space>
                      </Typography.Link>,
                    );
                  } else {
                    postActions.push(
                      <a onClick={() => toggleReplyState(item?.id ?? -1)} key={'reply'}>
                        <Space size={4}>
                          <MessageOutlined />
                          {item.commentNum}
                        </Space>
                      </a>,
                    );
                  }

                  return (
                    <>
                      <List.Item
                        itemID={index + ''}
                        styles={{
                          actions: {
                            marginLeft: '50px',
                          },
                        }}
                        actions={postActions}
                      >
                        <List.Item.Meta
                          avatar={
                            <Avatar size={'large'} src={item.user?.avatar ?? DEFAULT_AVATAR} />
                          }
                          title={item.user?.username ?? '无名氏'}
                          description={<span key={'time'}>{dayjs(item.createTime).fromNow()}</span>}
                        />
                        <div style={{ marginLeft: '50px' }}>
                          <div className={'text-base'}>
                            <a href={`/essay/detail/${item.id}` } target={'_blank'} rel="noreferrer">{item.content}</a>
                          </div>
                          <Space size={'middle'}>
                            {item.pictureList?.map((picture) => (
                              <Image key={picture} className={'z-0'} width={80} src={picture} />
                            ))}
                          </Space>
                        </div>
                      </List.Item>
                      {/*回复评论Card*/}
                      {isReplying ? (
                        <div style={{ marginLeft: '50px', marginTop: '8px' }}>
                          <CommentCard
                            avatar={false}
                            targetId={item.id}
                            type={'post'}
                            callback={async () => {
                              await loadPostData(postSortedField);
                              toggleReplyState(item?.id ?? -1);
                            }}
                          />
                        </div>
                      ) : (
                        <></>
                      )}
                    </>
                  );
                }}
              />
            </InfiniteScroll>
          </Card>
        </Card>
      </div>
    </Flex>
  );
};

export default EssayPostCard;
